You are currently looking at version 1.5 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook FAQ course resource.
This assignment requires more individual learning then the last one did - you are encouraged to check out the pandas documentation to find functions or methods you might not have used yet, or ask questions on Stack Overflow and tag them as pandas and python related. And of course, the discussion forums are open for interaction with your peers and the course staff.
Load the energy data from the file Energy Indicators.xls
, which is a list of indicators of energy supply and renewable electricity production from the United Nations for the year 2013, and should be put into a DataFrame with the variable name of energy.
Keep in mind that this is an Excel file, and not a comma separated values file. Also, make sure to exclude the footer and header information from the datafile. The first two columns are unneccessary, so you should get rid of them, and you should change the column labels so that the columns are:
['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']
Convert Energy Supply
to gigajoules (there are 1,000,000 gigajoules in a petajoule). For all countries which have missing data (e.g. data with "...") make sure this is reflected as np.NaN
values.
Rename the following list of countries (for use in later questions):
"Republic of Korea": "South Korea",
"United States of America": "United States",
"United Kingdom of Great Britain and Northern Ireland": "United Kingdom",
"China, Hong Kong Special Administrative Region": "Hong Kong"
There are also several countries with numbers and/or parenthesis in their name. Be sure to remove these,
e.g.
'Bolivia (Plurinational State of)'
should be 'Bolivia'
,
'Switzerland17'
should be 'Switzerland'
.
Next, load the GDP data from the file world_bank.csv
, which is a csv containing countries' GDP from 1960 to 2015 from World Bank. Call this DataFrame GDP.
Make sure to skip the header, and rename the following list of countries:
"Korea, Rep.": "South Korea",
"Iran, Islamic Rep.": "Iran",
"Hong Kong SAR, China": "Hong Kong"
Finally, load the Sciamgo Journal and Country Rank data for Energy Engineering and Power Technology from the file scimagojr-3.xlsx
, which ranks countries based on their journal contributions in the aforementioned area. Call this DataFrame ScimEn.
Join the three datasets: GDP, Energy, and ScimEn into a new dataset (using the intersection of country names). Use only the last 10 years (2006-2015) of GDP data and only the top 15 countries by Scimagojr 'Rank' (Rank 1 through 15).
The index of this DataFrame should be the name of the country, and the columns should be ['Rank', 'Documents', 'Citable documents', 'Citations', 'Self-citations', 'Citations per document', 'H index', 'Energy Supply', 'Energy Supply per Capita', '% Renewable', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015'].
This function should return a DataFrame with 20 columns and 15 entries.
In [1]:
def print_full(x):
pd.set_option('display.max_rows', len(x))
print(x)
pd.reset_option('display.max_rows')
In [2]:
def get_energy():
import pandas as pd
import numpy as np
energy = pd.read_excel('Energy Indicators.xls', skiprows=16, skip_footer=38, usecols=range(2,6), names=['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable'])
energy.drop(energy.index[0], inplace=True)
energy.replace('...', np.nan, inplace=True)
energy['Energy Supply'] = energy['Energy Supply'] * 1000000
energy['Country'] = energy['Country'].str.replace('\d+', '')
energy['Country'] = energy['Country'].str.replace(r"\s\(.*\)","")
di = {"Republic of Korea": "South Korea", "United States of America": "United States", "United Kingdom of Great Britain and Northern Ireland": "United Kingdom", "China, Hong Kong Special Administrative Region": "Hong Kong"}
energy["Country"].replace(di, inplace=True)
return energy
In [3]:
def get_gdp():
import pandas as pd
import numpy as np
GDP = pd.read_csv('world_bank.csv', header=4, usecols=['Country Name', 'Country Code', 'Indicator Code', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014','2015'])
di = {"Korea, Rep.": "South Korea", "Iran, Islamic Rep.": "Iran", "Hong Kong SAR, China": "Hong Kong"}
GDP["Country Name"].replace(di, inplace=True)
GDP.rename(columns={'Country Name':'Country'}, inplace=True)
return GDP
In [4]:
def get_ScimEn():
import pandas as pd
import numpy as np
ScimEn = pd.read_excel('scimagojr-3.xlsx')
return ScimEn
In [5]:
def answer_one():
import pandas as pd
import numpy as np
energy = get_energy()
GDP = get_gdp()
ScimEn = get_ScimEn()
base = pd.merge(ScimEn.head(16), energy, how='inner')
answer = pd.merge(base, GDP)
answer.set_index('Country', inplace=True)
del answer['Country Code']
del answer['Indicator Code']
return answer
answer_one()
Out[5]:
In [6]:
%%HTML
<svg width="800" height="300">
<circle cx="150" cy="180" r="80" fill-opacity="0.2" stroke="black" stroke-width="2" fill="blue" />
<circle cx="200" cy="100" r="80" fill-opacity="0.2" stroke="black" stroke-width="2" fill="red" />
<circle cx="100" cy="100" r="80" fill-opacity="0.2" stroke="black" stroke-width="2" fill="green" />
<line x1="150" y1="125" x2="300" y2="150" stroke="black" stroke-width="2" fill="black" stroke-dasharray="5,3"/>
<text x="300" y="165" font-family="Verdana" font-size="35">Everything but this!</text>
</svg>
In [7]:
def answer_two():
#227
import pandas as pd
import numpy as np
energy = get_energy()
GDP = get_gdp()
ScimEn = get_ScimEn()
base = pd.merge(ScimEn, energy, how='inner')
answer = pd.merge(base, GDP, how='inner')
base1 = pd.merge(ScimEn, energy, how='outer')
answer1 = pd.merge(base, GDP, how='outer')
return (len(answer1) - len(answer))
Answer the following questions in the context of only the top 15 countries by Scimagojr Rank (aka the DataFrame returned by answer_one()
)
In [8]:
def answer_three():
Top15 = answer_one()
Top15['avgGDP'] = Top15[['2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015']].mean(axis=1)
return Top15['avgGDP'].sort_values(ascending=False)
In [9]:
def answer_four():
Top15 = answer_one()
answer = Top15['2015'].iloc[3] - Top15['2006'].iloc[3]
return answer
answer_four()
Out[9]:
In [10]:
def answer_five():
Top15 = answer_one()
return Top15['Energy Supply per Capita'].mean()
In [28]:
def answer_six():
Top15 = answer_one()
answer = (Top15['% Renewable'].idxmax(), Top15['% Renewable'].max())
return answer
answer_six()
Out[28]:
In [31]:
def answer_seven():
Top15 = answer_one()
Top15['Cita_ratio'] = Top15['Self-citations']/Top15['Citations']
answer = (Top15['Cita_ratio'].idxmax(), Top15['Cita_ratio'].max())
return answer
answer_seven()
Out[31]:
In [32]:
def answer_eight():
Top15 = answer_one()
Top15['Pop_est'] = Top15['Energy Supply']/Top15['Energy Supply per Capita']
answer = Top15['Pop_est'].sort_values(ascending=False)
return answer.index[2]
answer_eight()
Out[32]:
Create a column that estimates the number of citable documents per person.
What is the correlation between the number of citable documents per capita and the energy supply per capita? Use the .corr()
method, (Pearson's correlation).
This function should return a single number.
(Optional: Use the built-in function plot9()
to visualize the relationship between Energy Supply per Capita vs. Citable docs per Capita)
In [38]:
def answer_nine():
Top15 = answer_one()
Top15['Pop_est'] = Top15['Energy Supply']/Top15['Energy Supply per Capita']
Top15['Est_cite_doc'] = Top15['Citable documents']/Top15['Pop_est']
answer = Top15.corr().iloc[8,-1]
return answer
answer_nine()
Out[38]:
In [39]:
#
In [40]:
#plot9() # Be sure to comment out plot9() before submitting the assignment!
Create a new column with a 1 if the country's % Renewable value is at or above the median for all countries in the top 15, and a 0 if the country's % Renewable value is below the median.
This function should return a series named HighRenew
whose index is the country name sorted in ascending order of rank.
In [79]:
def answer_ten():
import pandas as pd
import numpy as np
Top15 = answer_one()
Top15['HighRenew'] = np.where(Top15['% Renewable'] >= (Top15['% Renewable'].median()), 1, 0)
return Top15['HighRenew']
answer_ten()
#df = df.set_index('STNAME').groupby(level=0)['CENSUS2010POP'].agg({'avg': np.average})
#pd.cut(df['avg'],5, labels =['Tiny', 'Small', 'Medium', 'Large', 'Heouge'] )
Out[79]:
Use the following dictionary to group the Countries by Continent, then create a dateframe that displays the sample size (the number of countries in each continent bin), and the sum, mean, and std deviation for the estimated population of each country.
ContinentDict = {'China':'Asia',
'United States':'North America',
'Japan':'Asia',
'United Kingdom':'Europe',
'Russian Federation':'Europe',
'Canada':'North America',
'Germany':'Europe',
'India':'Asia',
'France':'Europe',
'South Korea':'Asia',
'Italy':'Europe',
'Spain':'Europe',
'Iran':'Asia',
'Australia':'Australia',
'Brazil':'South America'}
This function should return a DataFrame with index named Continent ['Asia', 'Australia', 'Europe', 'North America', 'South America']
and columns ['size', 'sum', 'mean', 'std']
In [18]:
def answer_eleven():
Top15 = answer_one()
return "ANSWER"
Cut % Renewable into 5 bins. Group Top15 by the Continent, as well as these new % Renewable bins. How many countries are in each of these groups?
This function should return a Series with a MultiIndex of Continent
, then the bins for % Renewable
. Do not include groups with no countries.
In [19]:
def answer_twelve():
Top15 = answer_one()
return "ANSWER"
Convert the Population Estimate series to a string with thousands separator (using commas). Do not round the results.
e.g. 317615384.61538464 -> 317,615,384.61538464
This function should return a Series PopEst
whose index is the country name and whose values are the population estimate string.
In [70]:
def answer_thirteen():
Top15 = answer_one()
Top15['PopEst'] = Top15['Energy Supply']/Top15['Energy Supply per Capita']
answer = Top15['PopEst'].sort_values(ascending=False)
PopEst = answer.map('{:,}'.format)
return PopEst
#answer.astype('str')
answer_thirteen()
Out[70]:
In [21]:
def plot_optional():
import matplotlib as plt
%matplotlib inline
Top15 = answer_one()
ax = Top15.plot(x='Rank', y='% Renewable', kind='scatter',
c=['#e41a1c','#377eb8','#e41a1c','#4daf4a','#4daf4a','#377eb8','#4daf4a','#e41a1c',
'#4daf4a','#e41a1c','#4daf4a','#4daf4a','#e41a1c','#dede00','#ff7f00'],
xticks=range(1,16), s=6*Top15['2014']/10**10, alpha=.75, figsize=[16,6]);
for i, txt in enumerate(Top15.index):
ax.annotate(txt, [Top15['Rank'][i], Top15['% Renewable'][i]], ha='center')
print("This is an example of a visualization that can be created to help understand the data. \
This is a bubble chart showing % Renewable vs. Rank. The size of the bubble corresponds to the countries' \
2014 GDP, and the color corresponds to the continent.")
In [22]:
#plot_optional() # Be sure to comment out plot_optional() before submitting the assignment!